##这个脚本用来调试串口
import serial
import array
import os
import signal
from time import sleep
import re 

flag_stop = False

def onsignal_int(a,b):
    print("sigint!")
    global flag_stop
    flag_stop = True

def confir(str):
    for i in range(0,32):
        str=str.replace(chr(i),'')
    return str

signal.signal(signal.SIGINT, onsignal_int)
signal.signal(signal.SIGTERM, onsignal_int)

ser = serial.Serial('COM4', 115200, timeout = 1)
print("serial.isOpen() =",ser.isOpen())


cmd_back = B""
cmd_length = 0x00
cmd_count = 0x00

##s = ser.write(("A20B01000000ADEFA50B01020000CB8D").encode('utf-8'))
curIndex = 0

while True:
    sleep(0.1)
    
   
    if flag_stop:                # read data until Ctrl+c
        #ser.write(stop)            # send cmd stop before exit
        print("reset cmd has been sent!")
        break
   
    text = ser.read(1)          # read one, with timout
    if text:                    # check if not timeout
        sleep(0.01)
        n = ser.inWaiting()     # look if there is more to read
        if n:
            text = text + ser.read(n) #get it
        cmd_back = cmd_back + text
        text = B""
        #s = ser.write(("A20B000000009ADF").encode("GBK"))
##        s = ser.write( B"\xA2\x0B\x00\x00\x00\x00\x9A\xDF" )
##        s = ser.write(b"\xA20B000000009ADF")
##        print("send")
##        break

    if len(cmd_back) < 7:        # go back if no enough data recvd
        #print("长度 %d"%(len(cmd_back)))
        continue
    
    print("==> %s cmds recvd."%(cmd_back))
    
    if(cmd_back == B"\xA2\x55\x01\x00\x00\x7A\x8E"):#开机
       s = ser.write(B"\xA2\x0B\x01\x00\x00\x00\xAD\xEF\xA5\x0B\x01\x02\x00\x00\xCB\x8D")
       curIndex = 0

    elif(cmd_back == B"\xA2\x55\x00\x00\x55\x47\xEE"): #关机
        s = ser.write(B"\xA2\x0B\x00\x00\x00\x00\x9A\xDF")
        curIndex = 0
                       #0xA3,0x55,0x01,0x00,0x00,0x7A,0x8E
    elif(cmd_back == B"\xA3\x55\x01\x00\x00\x7A\x8E"): #下一画面
        curIndex = curIndex + 1
                
    elif(cmd_back == B"\xA3\x55\x00\x00\x00\x4D\xBE"): #上一画面
        curIndex = curIndex - 1
##unsigned char returnStr1[] = {0xA5,0x0B,0x02,0x02,0x00,0x00,0x92,0xDD};
##unsigned char returnStr2[] = {0xA5,0x0B,0x03,0x02,0x00,0x00,0xA5,0xED};
##unsigned char returnStr3[] = {0xA5,0x0B,0x04,0x02,0x00,0x00,0x20,0x7D};
##unsigned char returnStr4[] = {0xA5,0x0B,0x05,0x02,0x00,0x00,0x17,0x4D};
##unsigned char returnStr5[] = {0xA5,0x0B,0x06,0x02,0x00,0x00,0x4E,0x1D};
    print(curIndex)
    if(curIndex == 1):
        s = ser.write(B"\xA5\x0B\x02\x02\x00\x00\x92\xDD")
    elif(curIndex == 2):
         s = ser.write(B"\xA5\x0B\x03\x02\x00\x00\xA5\xED")
    elif(curIndex == 3): 
         s = ser.write(B"\xA5\x0B\x04\x02\x00\x00\x20\x7D")
    elif(curIndex == 4):
         s = ser.write(B"\xA5\x0B\x05\x02\x00\x00\x17\x4D")
    elif(curIndex == 5): 
         s = ser.write(B"\xA5\x0B\x06\x02\x00\x00\x4E\x1D")


    
    print("-------------")
    cmd_back = B""
    #break;
   
ser.close()
